<script lang="ts" setup>
import type { WeddingOrder, OrderQuery } from '#/api/wedding';
import { Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';
import {
  Button,
  message,
  Form,
  Input,
  Select,
  DatePicker,
  Popconfirm,
  Tag,
} from 'ant-design-vue';
import { ContentWrap } from '#/components/content-wrap';
import { VxeTable } from '#/adapter/vxe-table';
import { TableToolbar } from '#/components/table-toolbar';
import { useTableToolbar } from '#/hooks';
import { Download, Plus, RefreshCw, Search, Trash2 } from '@vben/icons';
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { $t } from '#/locales';
import {
  getOrderPage,
  deleteOrder,
  exportOrder,
} from '#/api/wedding';
import {
  columns,
  orderStatusOptions,
  getOrderStatusColor,
  getOrderStatusText,
} from './data';
import OrderDetail from './detail.vue';

const router = useRouter();
const loading = ref(true);
const list = ref<WeddingOrder[]>([]);
const total = ref(0);
const queryParams = reactive<OrderQuery>({
  pageNo: 1,
  pageSize: 10,
});
const queryFormRef = ref();
const exportLoading = ref(false);

const getList = async () => {
  loading.value = true;
  try {
    const data = await getOrderPage(queryParams);
    list.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 详情弹窗
const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: OrderDetail,
  destroyOnClose: true,
});

function handleCreate() {
  router.push('/wedding/order/create');
}

function handleView(row: WeddingOrder) {
  detailModalApi.setData(row).open();
}

async function handleDelete(row: WeddingOrder) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.orderId]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteOrder(row.orderId);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.orderId]),
      key: 'action_process_msg',
    });
    await getList();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<string[]>([]);
function handleRowCheckboxChange({ records }: { records: WeddingOrder[] }) {
  checkedIds.value = records.map((item) => item.orderId);
}

async function handleDeleteBatch() {
  if (checkedIds.value.length === 0) {
    message.warning('请选择要删除的订单');
    return;
  }
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting'),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    // 批量删除：逐个调用删除接口
    await Promise.all(checkedIds.value.map(id => deleteOrder(id)));
    checkedIds.value = [];
    message.success($t('ui.actionMessage.deleteSuccess'));
    await getList();
  } finally {
    hideLoading();
  }
}

async function handleExport() {
  try {
    exportLoading.value = true;
    const data = await exportOrder(queryParams);
    downloadFileFromBlobPart({ fileName: '婚礼订单列表.xls', source: data });
  } finally {
    exportLoading.value = false;
  }
}

const { hiddenSearchBar, tableToolbarRef, tableRef } = useTableToolbar();
onMounted(() => {
  getList();
});
</script>

<template>
  <Page auto-content-height>
    <DetailModal @success="getList" />

    <ContentWrap v-if="!hiddenSearchBar">
      <Form :model="queryParams" ref="queryFormRef" layout="inline">
        <Form.Item label="订单号" name="orderId">
          <Input
            v-model:value="queryParams.orderId"
            placeholder="请输入订单号"
            allowClear
            @pressEnter="handleQuery"
          />
        </Form.Item>
        <Form.Item label="客户姓名" name="customerName">
          <Input
            v-model:value="queryParams.customerName"
            placeholder="请输入客户姓名"
            allowClear
            @pressEnter="handleQuery"
          />
        </Form.Item>
        <Form.Item label="订单状态" name="status">
          <Select
            v-model:value="queryParams.status"
            placeholder="请选择状态"
            allowClear
            :options="orderStatusOptions"
          />
        </Form.Item>
        <Form.Item label="婚期开始" name="weddingDateStart">
          <DatePicker
            v-model:value="queryParams.weddingDateStart"
            placeholder="选择日期"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="婚期结束" name="weddingDateEnd">
          <DatePicker
            v-model:value="queryParams.weddingDateEnd"
            placeholder="选择日期"
            class="w-full"
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </Button>
          <Button @click="resetQuery" class="ml-2">
            <template #icon><RefreshCw /></template>
            重置
          </Button>
        </Form.Item>
      </Form>
    </ContentWrap>

    <ContentWrap>
      <TableToolbar ref="tableToolbarRef">
        <template #toolbar-buttons>
          <Button type="primary" @click="handleCreate">
            <template #icon><Plus /></template>
            创建订单
          </Button>
          <Button @click="handleDeleteBatch" danger :disabled="checkedIds.length === 0">
            <template #icon><Trash2 /></template>
            批量删除
          </Button>
          <Button @click="handleExport" :loading="exportLoading">
            <template #icon><Download /></template>
            导出
          </Button>
        </template>
      </TableToolbar>

      <VxeTable
        ref="tableRef"
        :loading="loading"
        :data="list"
        :columns="columns"
        border
        stripe
        @checkbox-change="handleRowCheckboxChange"
        @checkbox-all="handleRowCheckboxChange"
      >
        <template #status="{ row }">
          <Tag :color="getOrderStatusColor(row.status)">
            {{ getOrderStatusText(row.status) }}
          </Tag>
        </template>

        <template #action="{ row }">
          <Button type="link" size="small" @click="handleView(row)">
            详情
          </Button>
          <Popconfirm 
            title="确定删除吗？" 
            @confirm="handleDelete(row)"
            :disabled="row.status !== 'DRAFT' && row.status !== 'CANCELLED'"
          >
            <Button 
              type="link" 
              danger 
              size="small"
              :disabled="row.status !== 'DRAFT' && row.status !== 'CANCELLED'"
            >
              删除
            </Button>
          </Popconfirm>
        </template>
      </VxeTable>

      <div class="mt-4 flex justify-end">
        <a-pagination
          v-model:current="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          show-size-changer
          :show-total="(total) => `共 ${total} 条`"
          @change="getList"
        />
      </div>
    </ContentWrap>
  </Page>
</template>

